package com.sdkj.fixed.asset.hc.controller;


import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.sdkj.fixed.asset.api.hc.ReceiptCheckApi;
import com.sdkj.fixed.asset.api.hc.vo.in.ProductExtends;
import com.sdkj.fixed.asset.api.hc.vo.in.ReceiptCheckConfirmParams;
import com.sdkj.fixed.asset.api.hc.vo.in.ReceiptCheckGetPageParams;
import com.sdkj.fixed.asset.api.hc.vo.in.ReceiptCheckProductGetPageParams;
import com.sdkj.fixed.asset.api.hc.vo.out.GetApplyList;
import com.sdkj.fixed.asset.api.hc.vo.out.ReceiptCheckDetail;
import com.sdkj.fixed.asset.api.hc.vo.out.ReceiptCheckInfo;
import com.sdkj.fixed.asset.common.base.*;
import com.sdkj.fixed.asset.common.exception.LogicException;
import com.sdkj.fixed.asset.common.utils.TimeTool;
import com.sdkj.fixed.asset.hc.mapper.CategoryMapper;
import com.sdkj.fixed.asset.hc.mapper.UserManagementMapper;
import com.sdkj.fixed.asset.hc.service.ReceiptCheckService;
import com.sdkj.fixed.asset.hc.util.CacheUtil;
import com.sdkj.fixed.asset.hc.util.ExcelUtils;
import com.sdkj.fixed.asset.hc.util.RedisUtil;
import com.sdkj.fixed.asset.pojo.hc.*;
import com.sdkj.fixed.asset.pojo.hc.group.*;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * @author 史晨星
 * @ClassName: ReceiptCheckController
 * @Description: 入库单
 * @date 2020年7月20日
 */
@Validated
@RestController()
public class ReceiptCheckController extends BaseController<ReceiptCheck> implements ReceiptCheckApi {

    private static Logger log = LoggerFactory.getLogger(ReceiptCheckController.class);

    @Resource
    private ReceiptCheckService service;

    @Resource
    private HttpServletRequest request;

    @Resource
    private UserManagementMapper userManagementMapper;

    @Resource
    private CategoryMapper categoryMapper;

    @Override
    public BaseService<ReceiptCheck> getService() {
        return service;
    }

    @Resource
    private CacheUtil cacheUtil;

    @Resource
    private RedisUtil redisUtil;

    /**
     * 新增
     *
     * @param entity
     * @return
     */
    @Override
    public BaseResultVo add(@Validated({AddReceiptCheck.class}) ReceiptCheck entity) throws Exception {
        String token = request.getHeader("token");
        String userId = cacheUtil.getUser(token).getUserId();
        String orgId = cacheUtil.getUser(token).getCompanys().get(0).getCompanyId();
        entity.setCuser(userId);
        entity.setEuser(userId);
        entity.setEtime(DateUtil.now());
        entity.setCtime(DateUtil.now());
        entity.setOrgId(orgId);
        entity.setState(1);
        entity.setFinish(2);
        ReceiptCheck receiptCheck = new ReceiptCheck();
        boolean isLock = false;
        while (!isLock) {
            isLock = redisUtil.setnx("RECEIPTCHECK_ADD", 5000);
            if (isLock) {
                try {
                    receiptCheck = service.add(entity);
                    redisUtil.del("RECEIPTCHECK_ADD");
                } catch (Exception e) {
                    redisUtil.del("RECEIPTCHECK_ADD");
                    throw e;
                }
                continue;
            } else {
                Thread.sleep(5000);
            }
        }


        return BaseResultVo.success("success", receiptCheck.getId());
    }

    /**
     * 查看
     *
     * @param entity
     * @return
     */
    @Override
    public BaseResultVo view(@Validated({DelReceiptCheck.class}) ReceiptCheck entity) throws Exception {
        ReceiptCheckInfo receiptCheckInfo = service.view(entity.getId());
        return BaseResultVo.success("success", receiptCheckInfo);
    }

    /**
     * 重新分配用户
     *
     * @param entity
     * @return
     */
    @Override
    public BaseResultVo edit(@Validated({EditReceiptCheck.class}) ReceiptCheck entity) throws Exception {
        String token = request.getHeader("token");
        String userId = cacheUtil.getUser(token).getUserId();
        String orgId = cacheUtil.getUser(token).getCompanys().get(0).getCompanyId();
        entity.setEuser(userId);
        entity.setCuser(userId);
        entity.setEtime(DateUtil.now());
        ReceiptCheck receiptCheck = service.setExecutor(entity);
        return BaseResultVo.success("success", receiptCheck.getId());
    }

    /**
     * 详情分页查询
     *
     * @param params
     * @return
     */
    @Override
    public BaseResultVo getPageDetail(@Validated PageParams<ReceiptCheckProductGetPageParams> params) throws Exception {
        List<ReceiptCheckDetail> receiptCheckDetailList = service.getPages(params);
        PageBean<ReceiptCheckDetail> page = new PageBean<>(receiptCheckDetailList);
        return BaseResultVo.success("success", page);
    }

    /**
     * 删除
     *
     * @param entity
     * @return
     */
    @Override
    public BaseResultVo del(@Validated({DelReceiptCheck.class}) ReceiptCheck entity) throws Exception {
        String token = request.getHeader("token");
        String userId = cacheUtil.getUser(token).getUserId();
        String orgId = cacheUtil.getUser(token).getCompanys().get(0).getCompanyId();
        entity.setEuser(userId);
        entity.setEtime(DateUtil.now());
        ReceiptCheck receiptCheck = service.del(entity);
        return BaseResultVo.success("success", receiptCheck.getId());
    }


    /**
     * 列表查询
     *
     * @param params
     * @return
     * @throws Exception
     */
    @Override
    public BaseResultVo getPages(@Validated PageParams<ReceiptCheckGetPageParams> params) throws Exception {
        String token = request.getHeader("token");
        String userId = cacheUtil.getUser(token).getUserId();
        String orgId = cacheUtil.getUser(token).getCompanys().get(0).getCompanyId();
        params.getParams().setOrgId(orgId);
        params.getParams().setUserId(userId);
        List<ReceiptCheck> receiptCheckList = service.getMainPages(params);
        PageBean<ReceiptCheck> page = new PageBean<>(receiptCheckList);
        return BaseResultVo.success(page);
    }


    /**
     * 新增盘盈
     *
     * @param entity
     * @return
     */
    @Override
    public BaseResultVo surplus(@Validated({Surplus.class}) ProductExtends entity) throws Exception {
        String token = request.getHeader("token");
        String userId = cacheUtil.getUser(token).getUserId();
        String orgId = cacheUtil.getUser(token).getCompanys().get(0).getCompanyId();
        entity.setCuser(userId);
        entity.setCtime(DateUtil.now());
        entity.setEuser(userId);
        entity.setEtime(DateUtil.now());
        entity.setOrgId(orgId);
        ReceiptCheckProduct receiptCheckProduct = service.surplus(entity);
        return BaseResultVo.success("success", receiptCheckProduct.getId());
    }

    /**
     * 编辑（手动盘点）
     *
     * @param entity
     * @return
     */
    @Override
    public BaseResultVo editCheckProduct(@Validated({EditCheckProduct.class}) ReceiptCheckProduct entity) throws Exception {
        String token = request.getHeader("token");
        String userId = cacheUtil.getUser(token).getUserId();
        String orgId = cacheUtil.getUser(token).getCompanys().get(0).getCompanyId();
        entity.setCheckUser(userId);
        ReceiptCheckProduct receiptCheckProduct = service.edit(entity);
        return BaseResultVo.success("success", receiptCheckProduct.getId());
    }

    /**
     * 没盘到
     *
     * @param entity
     * @return
     */
    @Override
    public BaseResultVo checkNone(@Validated({DelCheckProduct.class}) ReceiptCheckProduct entity) throws Exception {
        String token = request.getHeader("token");
        String userId = cacheUtil.getUser(token).getUserId();
        String orgId = cacheUtil.getUser(token).getCompanys().get(0).getCompanyId();
        entity.setCheckUser(userId);
        ReceiptCheckProduct receiptCheckProduct = service.checkNone(entity);
        return BaseResultVo.success("success", receiptCheckProduct.getId());
    }

    /**
     * 删除子盘点单（手动盘点）
     *
     * @param entity
     * @return
     */
    @Override
    public BaseResultVo delCheckProduct(@Validated({DelCheckProduct.class}) ReceiptCheckProduct entity) throws Exception {
        String token = request.getHeader("token");
        String userId = cacheUtil.getUser(token).getUserId();
        String orgId = cacheUtil.getUser(token).getCompanys().get(0).getCompanyId();
        ReceiptCheckProduct receiptCheckProduct = service.delCheckProduct(entity);
        return BaseResultVo.success("success", receiptCheckProduct.getId());
    }

    /**
     * 确认盘点结果
     *
     * @param entity
     * @return
     */
    @Override
    public BaseResultVo confirm(@Validated ReceiptCheckConfirmParams entity) throws Exception {
        String token = request.getHeader("token");
        String userId = cacheUtil.getUser(token).getUserId();
        String orgId = cacheUtil.getUser(token).getCompanys().get(0).getCompanyId();
        entity.setUserId(userId);
        entity.setOrgId(orgId);
        service.confirm(entity);
        return BaseResultVo.success("success");
    }

    /**
     * 列表查询App
     *
     * @param params
     * @return
     * @throws Exception
     */
    @Override
    public BaseResultVo getPagesApp(@Validated PageParams<ReceiptCheckGetPageParams> params) throws Exception {
        String token = request.getHeader("token");
        String userId = cacheUtil.getUser(token).getUserId();
        String orgId = cacheUtil.getUser(token).getCompanys().get(0).getCompanyId();
        params.getParams().setUserId(userId);
        params.getParams().setOrgId(orgId);
        if (params.getParams().getFinish()  == null) {
            throw new LogicException("是否完成（1完成2未完成）不能为空");
        }
        List<ReceiptCheck> pageList = service.getMainPages(params);
        for (ReceiptCheck receiptCheck : pageList) {
            receiptCheck.setCategoryName(categoryMapper.selectByPrimaryKey(receiptCheck.getCategoryId()).getName());
            receiptCheck.setCategoryCode(categoryMapper.selectByPrimaryKey(receiptCheck.getCategoryId()).getCode());
        }
        PageBean<ReceiptCheck> page = new PageBean<>(pageList);
        return BaseResultVo.success(page);
    }

    /**
     * 详情分页查询APP
     *
     * @param params
     * @return
     */
    @Override
    public BaseResultVo getPageDetailApp(@Validated PageParams<ReceiptCheckProductGetPageParams> params) throws Exception {
        List<ReceiptCheckDetail> receiptCheckDetailList = service.getPageDetailApp(params);
        PageBean<ReceiptCheckDetail> page = new PageBean<ReceiptCheckDetail>(receiptCheckDetailList);
        return BaseResultVo.success("success", page);
    }

    /**
     * 导出
     *
     * @param companyId
     * @param response
     * @throws Exception
     */
    @Override
    public void export(String companyId, String categoryId, String userId, HttpServletResponse response) throws Exception {
        List<ReceiptCheck> list = service.export(companyId, categoryId, userId);
        String fileName = "耗材盘点列表";
        ExcelUtils.exportExcel(list, fileName, fileName, ReceiptCheck.class, fileName + TimeTool.getTimeDate14(), response);
    }

    /**
     * 导出
     *
     * @param receiptId
     * @param response
     * @throws Exception
     */
    @Override
    public void exportDetail(String receiptId, HttpServletResponse response) throws Exception {
        List<ReceiptCheckDetail> list = service.exportDetail(receiptId);
        String fileName = "耗材盘点列表";
        ExcelUtils.exportExcel(list, fileName, fileName, ReceiptCheckDetail.class, fileName + TimeTool.getTimeDate14(), response);
    }
}

